<?php
namespace app\controller;

use app\BaseController;
use think\facade\View;
use think\Request;
use think\captcha\facade\Captcha;
use app\model\User;



class Login extends BaseController
{
    public function login(Request $request)
    {
        if ($this->request->isPost()) {
            $username = $request->post('username');
            $password = $request->post('password');
            $code = $request->post('captcha');

            //验证码验证
            $captcha = new Captcha();
            if(!$captcha::check($code)){
                return json([
                    'success' => false,
                    'message' => '验证码错误'
                ]);
            }

            if(empty($username) || empty($password)){
                return json(['success' => false, 'message' => '用户名或密码不能为空']);
            }

            // 验证用户名和密码
            $userModel = new User();
            $userInfo = $userModel->where('username',$username)->field('username,password')->find();

            if(empty($userInfo)){
                return json(['success' => false, 'message' => '用户不存在']);
            }

            if ($username !== $userInfo['username'] || md5(md5($password)) !== $userInfo['password']) {
                return json(['success' => false, 'message' => '用户名或密码错误']);
            }

            // 登录成功
            return json(['success' => true, 'message' => '登录成功']);
        }

        return View::fetch();
    }


    /**
     * 用户退出
     * @return mixed
     */
    public function out()
    {
        session('admin', null);
        $this->success('退出登录成功');
    }




}
